const soag = require('lilly-soag');
const services = require('../services');

const commonService = services.common;

module.exports = function (SysUserIdentify) {
  const login = SysUserIdentify.login.bind(SysUserIdentify);
  SysUserIdentify.login = function (provider, authScheme, profile, credentials,
    options, cb) {
    const { SysUser: userModel } = commonService.getModels();
    const filter = {
      where: { employeeId: profile.id },
    };
    commonService.getDetail(userModel, filter,
        (error, user) => {
          if (user != null) {
            login(provider, authScheme, { id: profile.id, emails: [{ value: user.email }] }, credentials,
              options, cb);
          } else {
            console.log(`LillyId: ${profile.id} 正在获取Soag相关详细`);
            soag.getUserProfile(profile.id)
            .then((res) => {
              if (res.data.length == 0) {
                console.log(`LillyId: ${profile.id} 没有获取到Soag相关信息。`);
              }
              const user = parse(res.data) || profile;
              login(provider, authScheme, user, credentials,
                options, cb);
            });
          }
        });
  };

  function parse([json]) {
    if (json == null) {
      return null;
    }

    if (typeof json == 'string') {
      json = JSON.parse(json);
    }

    const profile = {};
    profile.id = json.LillyID;
    profile.gender = json.Gender;
    profile.email = json.Email;
    if (json.Email) {
      profile.emails = [{ value: json.Email }];
    }
    profile.title = json.title;
    profile.baseLocation = json.BaseLocation;
    profile.chineseName = json.ChineseName;

    profile.SFTitle = json.SFTitle;
    profile.STTS_IND = json.STTS_IND;

    profile.globalID = json.GlobalID;
    profile.lillyID = json.LillyID;
    profile.isSupervisor = json.IsSupervisor;
    profile.managerID = json.ManagerID;
    profile.managerName = json.ManagerName;

    profile.company = json.Company;
    profile.contractorGroup = json.Contractorgroup;
    profile.department = json.Department;
    profile.subDepartment = json.SubDepartment;

    profile.createdAt = json.CRT_DT;
    profile.createdBy = json.CRT_USR;
    profile.updatedAt = json.UP_DT;
    profile.updateby = json.UP_USR;

    return profile;
  }
};
